package com.boxin.ims.modules.sys.scheduler;

import org.apache.log4j.Logger;

import it.sauronsoftware.cron4j.Scheduler;



/**
 * @author Jakemanse
 * time : 2012-12-6  下午2:31:09
 * 调度类
 */
public abstract class AbstractScheduler {
	
	protected final Logger logger = Logger.getLogger(getClass());
	protected SchedulerInfo schedulerInfo;
	protected Scheduler scheduler ;
	protected boolean isProcessing;
	
	public AbstractScheduler() {
		this.scheduler = new Scheduler();
	}
	
	/**
	 * @author Jakemanse
	 * @return
	 * @time 2013-1-1 下午2:00:30
	 * <p>function : 调度频率</p>
	 * @@return
	 */
	public abstract String frequency();
	
	/**
	 * @author Jakemanse
	 * 
	 * @time 2013-1-1 下午2:00:39
	 * <p>function : 调度处理</p>
	 * @
	 */
	public abstract void process();
	
	
	public   void stop(){
		if(scheduler!= null && scheduler.isStarted()){
			this.isProcessing = false;
			this.scheduler.stop();
			this.schedulerInfo.setStatus(0);
			logger.debug("停止调度成功...");
		}else{
			
			logger.debug("调度或已销毁或已停止...");
		}
	}
	
	
	public   void start(){
		checkAndInitScheduler();
		if(!scheduler.isStarted()){
			this.scheduler.schedule(this.frequency(), new Runnable() {
				@Override
				public void run() {
					process();
				}
			});
			this.schedulerInfo.setStatus(1);
			this.scheduler.start();
			
		}else {
			logger.debug("调度正在运行，无法启动...");
		}
	}
	
	private void checkAndInitScheduler(){
		if(scheduler == null){
			this.scheduler = new Scheduler();
			this.scheduler.setDaemon(true);
		}
	}
	
	
	public   void restart(){
		destroy();
		this.scheduler = new Scheduler();
		this.scheduler.setDaemon(true);
		this.start();
		
		logger.debug("立即执行同步。。。");
		this.process();
	}
	
	public   void destroy(){
		if(scheduler != null && scheduler.isStarted()){
			this.isProcessing = false;
			this.scheduler.stop();
			logger.debug("销毁调度成功！");
			this.scheduler = null;
			
		}
	}
	
	

	public SchedulerInfo getSchedulerInfo() {
		return schedulerInfo;
	}

	public void setSchedulerInfo(SchedulerInfo schedulerInfo) {
		this.schedulerInfo = schedulerInfo;
	}
	

}
